<!-- 游戏详情页 -->
<template>
    <div class="shell" v-if="game">
        <div class="she" style="background: linear-gradient(to right bottom, #1B2838 50%, #0C1219);">
            <div class="game">
                <!-- 游戏名称 -->
                <div class="tit">
                    <span>{{ game.gname }}</span>
                </div>
                <!-- 游戏图片展示 -->
                <div class="center">
                    <div class="left">
                        <transition name="fade" mode="out-in">
                            <img class="spic" :key="showPic" :src="showPic||`${game.photoa}`" />
                        </transition>
                        <div class="list-pic">
                            <img class="lpic" @mouseenter="showIndex(game.photoa)" :src="`${game.photoa}`" />
                            <img class="lpic" @mouseenter="showIndex(game.photob)" :src="`${game.photob}`" />
                            <img class="lpic" @mouseenter="showIndex(game.photoc)" :src="`${game.photoc}`" />
                            <img class="lpic" @mouseenter="showIndex(game.photod)" :src="`${game.photod}`" />
                        </div>
                    </div>
                    <!-- 游戏信息展示 -->
                    <div class="right">
                        <img :src="`${game.photo}`" />
                        <div class="info">
                            <span class="intro" :title="game.detail">
                                {{ game.detail }}
                            </span>
                            <div class="line" style="margin-bottom: 12px">
                                <span class="label">发行日期：</span>
                                <span class="val">{{ game.onsaledate }}</span>
                            </div>
                            <div class="line">
                                <span class="label">开发商：</span>
                                <span class="val comp">{{ game.company }}</span>
                            </div>
                            <div class="line">
                                <span class="label">发行商：</span>
                                <span class="val comp">{{ game.company }}</span>
                            </div>
                        </div>
                        <div class="tags">
                            <span class="tag" v-for="(v, i) in tags" :key="i"><span v-if="v != 'null'">{{ v }}</span></span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 两个购物按钮 -->
            <div class="shopping">
                <button @click="addCart">添加至您的购物车</button>
                <button @click="buyGame">立即购买</button>
            </div>
        </div>
        <!-- 评论区 -->
        <div class="comments">
            <!-- 游戏整体评分显示 -->
            <div class="overall-rating" v-if="commentList.length > 0">
                <div class="rating-score">
                    <span class="score">{{ overallRating.toFixed(1) }}</span>
                    <el-rate v-model="overallRating" disabled :colors="['#99A9B5', '#67B4dd', '#409EFF']" :allow-half="true" />
                </div>
                <div class="rating-text">{{ ratingText }}</div>
            </div>
            <div class="comments-header">
                <div class="comments-title">用户评论</div>
                <div class="filter-options">
                    <div class="rating-filter">
                        <el-select effect="dark" v-model="ratingFilter" placeholder="评分筛选" @change="applyFilters">
                            <el-option label="全部评分" value="0" />
                            <el-option label="5星" value="5" />
                            <el-option label="4星" value="4" />
                            <el-option label="3星" value="3" />
                            <el-option label="2星" value="2" />
                            <el-option label="1星" value="1" />
                        </el-select>
                    </div>
                    <div class="time-filter">
                        <el-select effect="dark" v-model="timeFilter" placeholder="时间排序" @change="applyFilters">
                            <el-option label="最新" value="newest" />
                            <el-option label="最早" value="oldest" />
                        </el-select>
                    </div>
                </div>
            </div>
            <!-- 发布评论 -->
            <div class="put-comment">
                <div class="rating-box">
                    <span class="rating-label">您的评分：</span>
                    <el-rate v-model="commentRating" :colors="['#99A9B5', '#67B4dd', '#409EFF']" />
                </div>
                <div class="comment-input">
                    <textarea 
                        v-model="commentContent" 
                        placeholder="分享您对这款游戏的看法..."
                        :disabled="submitting"
                    ></textarea>
                </div>
                <div class="comment-submit">
                    <button @click="submitComment" :disabled="submitting">
                        {{ submitting ? '发布中...' : '发表评论' }}
                    </button>
                </div>
            </div>
            <!-- 显示已发布的评论 -->
            <div class="p-comments" v-if="commentList.length > 0">
                <div class="comment-item" v-for="(comment) in filteredCommentList.slice((currentPage-1)*pageSize, currentPage*pageSize)" :key="comment.rid">
                    <div class="comment-header">
                        <div class="user-info">
                            <img class="avatar" :src="`${comment.memberAvatar}`" alt="用户头像">
                            <span class="username">{{ comment.memberName }}</span>
                        </div>
                        <div class="comment-rating">
                            <el-rate 
                                v-model="comment.rating" 
                                disabled 
                                :colors="['#99A9B5', '#67B4dd', '#409EFF']"
                            />
                        </div>
                    </div>
                    <div class="comment-content">
                        {{ comment.review }}
                    </div>
                    <div class="comment-footer">
                        <span class="comment-time">{{ formatDate(comment.reviewTime) }}</span>
                    </div>
                </div>
                <!-- 分页 -->
                <div class="pagination-container" v-if="totalComments > pageSize">
                    <el-pagination
                        background
                        layout="prev, pager, next"
                        :total="totalComments"
                        :page-size="pageSize"
                        v-model:current-page="currentPage"
                    />
                </div>
            </div>
            <div class="no-comments" v-else>
                暂无评论，快来发表第一条评论吧！
            </div>
        </div>


    </div>
</template>

<script>
import { ElLoading, ElPagination, ElRate } from "element-plus";
export default {
    data() {
        return {
            game: null,
            ordId: [],
            loadingInstance: null,
            showPic: '',
            // 评论相关数据
            commentList: [],
            filteredCommentList: [], // 筛选后的评论列表
            totalComments: 0,
            currentPage: 1,
            pageSize: 5,
            commentContent: '',
            commentRating: 3,
            submitting: false,
            // 筛选相关
            ratingFilter: '0', // 默认显示全部评分
            timeFilter: 'newest', // 默认按最新排序
            overallRating: 0 // 游戏整体评分
        }
    },
    mounted() {
        console.log(this.$store.state.allGame[this.$store.state.curGame])
        this.game = this.$store.state.allGame[this.$store.state.curGame];
        // 加载游戏评论
        this.fetchComments();
    },
    methods: {
        async addCart() {
            const query = {
                gid: this.game.gid,
                mid: this.$store.state.mid,
            }
            const that = this;
            await that.$axios.post('cart/addCart', query).then((response) => {
                console.log(response)
                if (response.status != 200) return that.$tools.alertMsg('系统错误', 'error');
                if (response.data.code == 200) {
                    that.$tools.alertMsg('成功添加至购物车', 'success', 1500);
                } else {
                    that.$tools.alertMsg(`添加至购物车失败，${response.data.message}`, 'warning', 1500);
                }
            }).catch(function (error) {
                console.log(error)
            })
        },
        // 创建单个订单
        async createOneOrd() {
            const query = {
                gid: this.game.gid,
            }
            const that = this;
            await that.$axios
                .post("order/createOrders", query)
                .then((response) => {
                    console.log(response);
                    if (response.status != 200)
                        return that.$tools.alertMsg("系统错误", "error");
                    if (response.data.code == 200) {
                        // this.ordId = response.data.data.oid;
                        this.payoff(response.data.data.oid); 
                    } else {
                        that.$tools.alertMsg("创建订单失败，可能已经购买", "error", 1500);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
        // 结算订单
        async payoff(oid) {
            const that = this;
            await that.$axios.post("mybox/saveMyBox",{oid}).then((response) => {
                console.log(response)
                if (response.status!= 200) return that.$tools.alertMsg('系统错误', 'error');
                if (response.data.code == 200) {
                    that.$tools.alertMsg("购买成功，游戏已入库", "success", 2000);
                } else {
                    that.$tools.alertMsg("执行请求时发生错误，结算失败", "error");
                }
            }).catch(function (error) {
                console.log(error)
            })
            // that.loadingInstance.close();
            

        },
        // 购买游戏
        async buyGame() {
            const loadOptions = { text: "购买中", background: "rgba(23,29,37,0.7)" };
            this.loadingInstance = ElLoading.service(loadOptions);
            await this.createOneOrd();
            this.loadingInstance.close();
        },
        // 显示当前聚焦图片
        async showIndex(pic){
            this.showPic = `${pic}`
        },
        
        // 获取游戏评论
        async fetchComments() {
            const that = this;
            if (!this.game) return;
            const query = {
                gid: this.game.gid
            }
            await that.$axios.get(`goods/getGoodsreview`,{params:query}).then((response) => {
                console.log('评论数据:', response);
                if (response.status === 200 && response.data.code === 200) {
                    that.commentList = response.data.data;
                    that.commentList.forEach(comment => {
                        if(!comment.memberAvatar.startsWith('http'))
                            comment.memberAvatar = `${that.$store.state.baseUrl}/${comment.memberAvatar}`;
                    });
                    that.totalComments = response.data.data.length;
                    that.calculateOverallRating();
                    that.applyFilters();
                } else {
                    that.$tools.alertMsg('获取评论失败', 'warning', 1500);
                }
            }).catch(function (error) {
                console.log(error);
                that.$tools.alertMsg('获取评论失败', 'error', 1500);
            });
        },
        
        // 计算游戏整体评分
        calculateOverallRating() {
            if (this.commentList.length === 0) {
                this.overallRating = 0;
                return;
            }
            
            const totalRating = this.commentList.reduce((sum, comment) => sum + comment.rating, 0);
            this.overallRating = totalRating / this.commentList.length;
        },
        
        // 应用筛选条件
        applyFilters() {
            let filtered = [...this.commentList];
            filtered.sort((a, b) => a.rating - b.rating);
            // 按评分筛选
            if (this.ratingFilter !== '0') {
                const ratingValue = parseInt(this.ratingFilter);
                filtered = filtered.filter(comment => comment.rating === ratingValue);
            }
            
            // 按时间排序
            if (this.timeFilter === 'newest') {
                filtered.sort((a, b) => new Date(b.reviewTime) - new Date(a.reviewTime));
            } else if (this.timeFilter === 'oldest') {
                filtered.sort((a, b) => new Date(a.reviewTime) - new Date(b.reviewTime));
            }
            
            this.filteredCommentList = filtered;
            this.totalComments = filtered.length;
            this.currentPage = 1; // 重置页码
        },
        
        // 发布评论
        async submitComment() {
            if (!this.commentContent.trim()) {
                this.$tools.alertMsg('评论内容不能为空', 'warning', 1500);
                return;
            }
            
            this.submitting = true;
            const query = {
                gid: this.game.gid,
                rating: this.commentRating,
                review: this.commentContent
            };
            
            const that = this;
            await that.$axios.post('/goods/addGoodsreview', query).then((response) => {
                console.log(response);
                if (response.status === 200 && response.data.code === 200) {
                    that.$tools.alertMsg('评论发布成功，审核通过后将显示', 'success', 2000);
                    that.commentContent = '';
                    that.commentRating = 3;
                    that.fetchComments(); // 重新加载评论
                } else {
                    that.$tools.alertMsg('评论发布失败', 'warning', 1500);
                }
            }).catch(function (error) {
                console.log(error);
                that.$tools.alertMsg('评论发布失败', 'error', 1500);
            }).finally(() => {
                that.submitting = false;
            });
        },
    
        
        // 格式化日期
        formatDate(dateStr) {
            const date = new Date(dateStr);
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        }
    },
    computed: {
        tags() {
            var str = this.game.moretype + '';
            return str.split(',');
        },
        ratingText() {
            if (this.overallRating < 2) {
                return "差评如潮";
            } else if (this.overallRating < 3) {
                return "褒贬不一";
            } else if (this.overallRating < 4) {
                return "多半好评";
            } else if (this.overallRating < 4.5) {
                return "特别好评";
            } else {
                return "好评如潮";
            }
        }
    }
}
</script>

<style lang="less" scoped>
.tags {
    display: flex;
    flex-wrap: wrap;
    max-height: 50px;
    overflow: hidden;
    margin: 10px 0px 6px 0px;

    .tag {
        background-color: #274051;
        font-size: 12px;
        padding: 3px 8px;
        margin: 1px 2px;
        border-radius: 3px;
        flex-shrink: 0;
        color: #67B4dd;
    }
}

.shell {
    height: calc(100vh - 72px);

    .game {
        max-width: 960px;
        margin: 20px auto;

        .tit {
            text-align: left;
            font-size: 26px;
            font-weight: bold;
            color: #fff;
            padding: 10px 0px;
        }

        .center {
            display: flex;
            width: 100%;
            height: 100%;

            .left {
                display: flex;
                flex-direction: column;
                width: 64%;
                height: 100%;

                .spic {
                    width: 100%;
                    height: 340px;
                    object-fit: cover;
                    margin-bottom: 6px;
                }

                .list-pic {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .lpic {
                        width: 24%;
                        height: 100px;
                        object-fit: cover;
                        cursor: pointer;
                    }
                }
            }

            .right {
                width: 36%;
                height: 100%;
                padding: 0px 12px;

                img {
                    width: 100%;
                    height: 180px;
                    object-fit: contain;
                    background-color: #111;
                    
                }

                .info {
                    display: flex;
                    flex-direction: column;
                    text-align: left;

                    .intro {
                        margin-top: 8px;
                        margin-bottom: 12px;
                        text-indent: 2em;
                        text-align: justify;
                        font-size: 16px;
                        color: #eee;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        -webkit-line-clamp: 5;
                    }

                    .line {
                        display: flex;
                        align-items: center;
                        margin: 1px 0px;

                        .label {
                            width: 50%;
                            font-size: 12px;
                            color: #556772;
                        }

                        .val {
                            width: 50%;
                            color: #8F98A0;
                            font-size: 14px;
                        }

                        .comp {
                            color: #67B4dd;
                        }
                    }
                }

            }
        }
    }

    .shopping {
        max-width: 960px;
        margin: 0px auto;
        text-align: left;
        padding: 0px 20px 10px 10px;
        box-sizing: border-box;

        button {
            background-color: #274051;
            font-size: 16px;
            padding: 5px 10px;
            margin: 1px 4px;
            border-radius: 3px;
            flex-shrink: 0;
            color: #67B4dd;
        }
    }
}
.fade-enter,
.fade-leave-to {
    opacity: 0;
}
.fade-enter-to,
.fade-leave {
    opacity: 1;
}
.fade-enter-active,
.fade-leave-active {
    transition: all 0.2s ease-in-out ;
}

/* 评论区样式 */
.comments {
    max-width: 960px;
    margin: 20px auto;
    padding: 20px;
    background: linear-gradient(to right bottom, #1B2838 50%, #0C1219);
    border-radius: 4px;
    color: #8F98A0;
    
    .overall-rating {
        background-color: rgba(39, 64, 81, 0.3);
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .rating-score {
            display: flex;
            align-items: center;
            
            .score {
                font-size: 32px;
                font-weight: bold;
                color: #67B4dd;
                margin-right: 15px;
            }
        }
        
        .rating-text {
            font-size: 20px;
            font-weight: bold;
            color: #67B4dd;
        }
    }
    
    .comments-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid #274051;
        
        .comments-title {
            font-size: 22px;
            font-weight: bold;
            color: #fff;
            text-align: left;
        }
        
        .filter-options {
            display: flex;
            gap: 10px;
            
            :deep(.el-input__wrapper) {
                background-color: rgba(27,51,78,0.5);
                box-shadow: 0 0 0 1px #274051 inset;
                
                &:hover {
                    box-shadow: 0 0 0 1px #67B4dd inset;
                }
                
                &.is-focus {
                    box-shadow: 0 0 0 1px #67B4dd inset;
                }
                
                .el-input__inner {
                    color: #ddd;
                }
            }
            
            :deep(.el-select-dropdown) {
                background-color: #1A2A3C;
                border: 1px solid #274051;
                
                .el-select-dropdown__item {
                    color: #ddd;
    
                    &.hover, &:hover {
                        background-color: #274051;
                    }
                    
                    &.selected {
                        color: #67B4dd;
                        background-color: #274051;
                    }
                }
            }
        }
    }
    
    .put-comment {
        background-color: rgba(39, 64, 81, 0.3);
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 20px;
        
        .rating-box {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            
            .rating-label {
                margin-right: 10px;
                color: #67B4dd;
            }
        }
        
        .comment-input {
            margin-bottom: 10px;
            
            textarea {
                width: 100%;
                box-sizing: border-box;
                height: 140px;
                background-color: #1A2A3C;
                border: 1px solid #274051;
                border-radius: 4px;
                color: #ddd;
                padding: 10px;
                resize: none;
                font-family: inherit;
                
                &:focus {
                    outline: none;
                    border-color: #67B4dd;
                }
                
                &::placeholder {
                    color: #556772;
                }
            }
        }
        
        .comment-submit {
            text-align: right;
            
            button {
                background-color: #274051;
                font-size: 16px;
                padding: 8px 15px;
                border-radius: 3px;
                color: #67B4dd;
                cursor: pointer;
                transition: background-color 0.2s;
                
                &:hover {
                    background-color: #335566;
                }
                
                &:disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                }
            }
        }
    }
    
    .p-comments {
        .comment-item {
            background-color: rgba(39, 64, 81, 0.2);
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            text-align: left;
            
            .comment-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10px;
                
                .user-info {
                    display: flex;
                    align-items: center;
                    
                    .avatar {
                        width: 40px;
                        height: 40px;
                        border-radius: 50%;
                        object-fit: cover;
                        margin-right: 10px;
                        background-color: #111;
                    }
                    
                    .username {
                        font-weight: bold;
                        color: #67B4dd;
                    }
                }
            }
            
            .comment-content {
                color: #ddd;
                margin: 10px 0;
                line-height: 1.5;
                word-break: break-word;
            }
            
            .comment-footer {
                font-size: 12px;
                color: #556772;
                text-align: right;
            }
        }
        
        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: center;
        }
    }
    
    .no-comments {
        text-align: center;
        padding: 30px 0;
        color: #556772;
        font-style: italic;
    }
}
</style>